package cn.scw.framework.security.filter;

import cn.scw.common.utils.SecurityUtils;
import cn.scw.common.utils.StringUtils;
import cn.scw.common.utils.Threads;
import cn.scw.common.utils.spring.SpringUtils;
import cn.scw.framework.security.LoginUser;
import cn.scw.framework.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * token过滤器 验证token有效性
 * 
 * @author api
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        //跨域预检测请求是options方法则直接返回200
        if ("OPTIONS".equals(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "Accept, Origin, X-Requested-With, Content-Type,Last-Modified,SessionId,"+tokenService.header);
            response.setStatus(HttpStatus.OK.value());
        } else {
            setLanguage(request,response);

            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            chain.doFilter(request, response);
        }
    }

    /**
     * 设置多语言
     * @param request
     */

    private void setLanguage(HttpServletRequest request,HttpServletResponse response) {
        //默认语言
        Threads.setLanguage(LocaleContextHolder.getLocale().toLanguageTag());

        String language = request.getHeader("language");

        if(null!=language){
            Locale locale=Locale.forLanguageTag(language);
            if(language.equals(locale.toLanguageTag())){
                //更新语言
                Threads.setLanguage(language);
                SessionLocaleResolver localeResolver=SpringUtils.getBean(SessionLocaleResolver.class);
                localeResolver.setLocale(request,response,locale);
            }
        }
    }
}
